import axios from 'axios'
import { apiUrl } from '../../config/base'

/**
 * Create Axios
 */
const http = axios.create({
  baseURL: apiUrl
})

/**
 * Set static headers
 */
http.defaults.headers.common = {
  'X-Requested-With': 'XMLHttpRequest',
  'Accept': 'application/json'
}

/**
 * Add dynamic headers
 */
http.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer ' + localStorage.getItem('api_token')
  config.headers['X-CSRF-TOKEN'] = localStorage.getItem('csrf_token')
  return config
})

/**
 * Handle all error messages.
 */
http.interceptors.response.use(response => {
  return response
}, error => {
  // 未授权后直接跳转
  if (error.response.status === 401) {
    localStorage.clear()
    error = Object.assign(error.response, { data: '登录令牌已失效，请重新登录！' })
    return Promise.reject(error)
  }
  return Promise.reject(error.response)
})

export default function install (Vue) {
  Object.defineProperty(Vue.prototype, '$http', { value: http })
}
